<template>
  <div class="layout">
    <!-- 左侧导航栏 -->
    <div class="left-nav">
      <div><slot></slot></div>
      <div class="nav-title">
        <span class="nav-text">分组管理</span>
        <el-tooltip content="添加分组">
          <el-icon color="#FF6B00" @click="addGroup(firstId, false)"><plus /></el-icon>
        </el-tooltip>
      </div>
      <div class="groups block">
        <el-input class="search_group" v-model="filterText" placeholder="请输入分组名称进行查找" />
        <el-tree ref="treeRef" class="filter-tree" :data="groupData" :props="defaultProps" :filter-node-method="filterNode" :default-expand-all="true">
          <template #default="{ node, data }">
            <el-tooltip placement="right" effect="light">
              <template #content>
                <template v-if="data.name == '默认分组'">
                  <div><el-link class="link-text" :underline="false" type="primary" @click="addGroup(data, false)">添加子分组</el-link></div>
                </template>
                <template v-else>
                  <div><el-link class="link-text" v-if="!data.pid" :underline="false" type="primary" @click="addGroup(data, false)">添加子分组</el-link></div>
                  <!-- <div><el-link class="link-text" v-if="!data.pid" :underline="false" type="primary" @click="addGroup(data, false)">添加子分组</el-link></div> -->
                  <template v-if="data.name != '全部分组'">
                    <div><el-link class="link-text" :underline="false" type="primary" @click="addGroup(data, true)">编辑</el-link></div>
                    <div><el-link class="link-text" :underline="false" type="primary" @click="removeGroup(data)">删除</el-link></div>
                  </template>
                  <!-- <el-link class="link-text" :underline="false" type="primary" v-show="data.is_local">同步至企微</el-link> -->
                </template>
              </template>
              <div class="hover-text" @mouseover="mouseOver(data)" @mouseleave="mouseLeave(data)" @click="changeData(data)">
                <div :class="selectId == data.id ? 'hover-detail-color' : 'hover-detail'">
                  <!-- {{ `${data.name}（${data.nums}）` }} -->
                  {{ data.name }}
                </div>
                <el-icon color="#FF6B00" class="hover-icon" v-show="data.showEdit"><more-filled /></el-icon>
              </div>
            </el-tooltip>
          </template>
        </el-tree>
      </div>
    </div>
    <!-- 添加分组 -->
    <Dialog :appDialog="appDialog">
      <el-form ref="ruleFormRef" :model="addGroupingForm" :rules="rules" label-width="120px" class="demo-ruleForm">
        <!-- :size="formSize" -->
        <el-form-item label="选择分组" prop="selectGroup">
          <el-cascader v-model="addGroupingForm.selectGroup" :options="options" :props="defaultProps" placeholder="请选择分组" filterable @expand-change="ceateChageGroup" />
        </el-form-item>
        <el-form-item label="分组名称" prop="name">
          <el-input v-model="addGroupingForm.name" placeholder="请输入分组名称" maxlength="12" show-word-limit clearable></el-input>
        </el-form-item>
      </el-form>
    </Dialog>
    <!-- 删除弹框 -->
    <ZWDeletdialog ref="groupDialogRef" @submit="delBtn" />
  </div>
</template>

<script setup lang="ts">
  import { ref, watch, reactive, onMounted, computed } from 'vue'
  import { ElMessage, ElTree, ElForm } from 'element-plus'
  import Dialog from '@renderer/components/Dialog.vue'
  import ZWDeletdialog from '@renderer/components/ZWDeletdialog.vue'
  // import { addGroup, editGroup, delGroup, getGroupList } from '@renderer/api/concreation'
  // import { getMarketinGroupgList } from '@renderer/api/smartMarketing/group'
  import { getGroupList, createGroup, delGroup, editGroup } from '@renderer/ajax/api/common'
  import { useStore } from '@renderer/store'
  const ruleFormRef = ref<InstanceType<typeof ElForm>>()
  const treeRef = ref<InstanceType<typeof ElTree>>()
  const emit = defineEmits(['submit'])
  const store = useStore()
  const groupDialogRef: any = ref(null)
  interface Tree {
    id: number
    name: string
    children?: Tree[]
  }
  const selectId: any = ref('all')
  const filterText = ref('') // 搜索分组
  const showEdit = ref(false) //是否展示部门编辑
  const isUpdate = ref(false) //是否是编辑弹框
  const firstId = ref(0)
  const pId = ref(4) //父元素ID
  const type = ref(100)
  const getParentId = (key: number, data: any[]) => {
    let flag: boolean = false
    data.forEach((item: any) => {
      if (item.id == key) {
        flag = true
      } else {
        if (item.children && item.children.length > 0) {
          let res = getParentId(key, item.children)
          if (res) pId.value = item.id
        }
      }
    })
    return flag
  }
  // 取消按钮
  const cancelHandel = () => {
    appDialog.visible = false
    isUpdate.value = false
    // ruleFormRef.value.resetFields()
  }
  // 保存按钮
  const submitHandel = () => {
    console.log(addGroupingForm, '添加-------------')

    ruleFormRef.value.validate(async (valid: any) => {
      if (valid) {
        let key = isUpdate.value ? 'group_id' : 'pid'
        let params = {
          type: type.value,
          name: addGroupingForm.name,
          group_id: selectId.value,
          pid: addGroupingForm.selectGroup == 'all' ? 0 : addGroupingForm.selectGroup
        }
        console.log(params, isUpdate.value, '=状态----------===')
        isUpdate.value ? await editGroup(params) : await createGroup(params)
        ElMessage.success(`${isUpdate.value ? '更新' : '创建'}分组成功`)
        getGroup()
        cancelHandel()
      }
    })
  }
  const ceateChageGroup = (val: any) => {
    console.log(val, 2222)
  }
  // 弹框相关配置
  const appDialog = reactive({
    visible: false,
    title: `创建分组`,
    width: '500px',
    cancel: cancelHandel,
    submit: submitHandel,
    cancelText: '取消',
    submitText: '保存'
  })
  // 添加分组表单
  const addGroupingForm = reactive({
    selectGroup: 0, // 选择分组
    name: '' // 添加分组名称
  })
  // 添加分组校验规则
  const rules = {
    name: [
      {
        required: true,
        message: '请填写分组名称',
        trigger: 'blur'
      }
    ]
  }

  const defaultProps = {
    checkStrictly: true,
    emitPath: false,
    label: 'name',
    value: 'id'
  }

  watch(filterText, (val) => {
    treeRef.value!.filter(val)
  })
  // 搜索分组
  const filterNode = (value: string, data: Tree) => {
    if (!value) return true
    return data.name.indexOf(value) !== -1
  }
  // 分组 tree
  const groupData = ref([])
  const options = ref([])
  //鼠标移入
  const mouseOver = (data: any) => {
    // selectId.value = data.id
    data.showEdit = true
  }
  //鼠标移出
  const mouseLeave = (data: any) => {
    // selectId.value = 0
    data.showEdit = false
  }
  //切换id
  const changeData = (data: any) => {
    console.log(data.id, '切换分组 id-------------')
    selectId.value = data.id
    emit('submit', data.id)
    // store.dispatch('content/group', {
    //   groupId: data.id
    // })
    getGroup()
  }

  // 新增/编辑分组的弹框
  const addGroup = (data: any, flag?: boolean) => {
    console.log(data, '分组---------------1111', flag || false)
    // getParentId(data.id, groupData.value)
    isUpdate.value = flag
    appDialog.title = `${flag ? '更新' : '创建'}分组`
    selectId.value = data.id
    addGroupingForm.selectGroup = data.pid ? data.pid : data.id || 0
    // addGroupingForm.selectGroup = data.id
    addGroupingForm.name = flag ? data.name : ''
    appDialog.visible = true
  }
  // 删除
  const removeGroup = (data: any) => {
    selectId.value = data.id
    groupDialogRef.value.appDialog.visible = true
  }
  // 删除分组确认按钮
  const delBtn = () => {
    delGroup({
      group_id: selectId.value
    }).then((res: any) => {
      groupDialogRef.value.appDialog.visible = false
      ElMessage.success(`删除分组成功`)
      getGroup()
    })
  }
  // 获取分组列表详情
  const getGroup = async () => {
    // getGroupList({type: ,})
    const res: any = await getGroupList({ type: type.value, name: '' })
    console.log(res, '分组列表')
    let defaultId = res.data[0].id
    let result: any[] = [
      {
        name: '全部分组',
        id: 'all',
        nums: 0,
        children: []
      }
    ]
    if (res.data.length > 0) {
      result[0].nums = res.total
      result[0].children = res.data
    }
    // store.dispatch('content/group', {
    //   groupList: result,
    //   groupId: defaultId
    // })
    // emit('getTotal', res.total)
    // store.dispatch("luckyDraw/group", {
    //   groupList: result,
    //   groupId: defaultId,
    // });

    firstId.value = defaultId
    groupData.value = result
    // groupData.value = result.children.map((item) => {
    //   delete item.children
    // })
    let arrs = JSON.parse(JSON.stringify(result))
    let arr: any = []
    arrs[0].children.forEach((item: any) => {
      delete item.children
      arr.push(item)
    })
    let resData: any = [
      {
        name: '全部分组',
        id: 'all',
        nums: 0,
        children: arr
      }
    ]
    options.value = resData
    console.log(options, 'arrarrrrrrrrr')
    // options.value =
  }
  // const SetGetGroup = (val: any) => {
  //   type.value = val
  //   getGroup()
  // }
  onMounted(() => {
    getGroup()
    console.log('分组列表')
  })
  // defineExpose({
  //   getGroup,
  //   SetGetGroup,
  //   selectId
  // })
</script>

<style lang="scss" scoped>
  .layout {
    // display: flex;
    height: 100%;
    .left-nav {
      // width: 270px;
      height: 100%;
      box-sizing: border-box;
      // height: 600px;
      border: 1px solid #eaeaea;
      background-color: #ffffff;
      padding: 16px;
      margin-right: 16px;
      // box-shadow: 0px 0.5px 10px rgba(0, 0, 0, 0.2);
      .nav-title {
        display: flex;
        justify-content: space-between;
        margin-bottom: 10px;
      }
      .nav-text {
        font-size: 16px;
        font-weight: 600;
        color: #33302d;
      }
      .nav-input {
        width: 238px;
        padding: 16px 0 20px 0;
      }
      .el-tree-node__content {
        height: 35px !important;
      }
      .hover-text {
        width: 100%;
        display: flex;
        justify-content: space-between;
        align-items: center;
        .hover-detail {
          color: #535456;
          font-size: 14px;
        }
        .hover-detail-color {
          color: #ff6b00;
        }
        .hover-detail:hover {
          color: #ff6b00;
        }
        .hover-icon {
          transform: rotate(90deg);
        }
      }
      .search-list {
        display: flex;
        flex-direction: column;
        .search-detail {
          margin: 0;
          color: #33302d;
        }
        .search-detail:hover {
          background-color: #f5f7fa;
        }
        .hover-text {
          line-height: 35px;
        }
      }
      .no-data {
        display: flex;
        flex-direction: column;
        align-items: center;
        .nodata-img {
          margin: 30px 0 30px 15px;
          width: 150px;
          height: 120px;
        }
      }
      .groups {
        color: #33302d;
        font-size: 14px;
        .search_group {
          margin: 20px 0;
        }
        // .hover_box {
        //   display: flex;
        //   flex-direction: column;
        //   align-items: center;
        //   justify-content: center;
        //   .hover_btn {
        //     color: #ff6b00 !important;
        //   }
        // }
        :deep .el-tree-node__expand-icon {
          color: #ff6b00;
        }
        :deep .el-tree-node__content:hover {
          background: #fffaf9;
        }
        :deep .el-tree {
          --el-tree-node-hover-bg-color: #fffaf9;
        }
      }
      :deep.el-popper {
        text-align: center !important;
      }
    }
  }
</style>
